package com.happy016.config;


import com.happy016.annotation.SelfAnno;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @SelfAnno 注解规则定义类
 * @author Linyb
 * @since 2017/9/25 15:48
 */
@Configuration
public class SelfAnnoHandler extends HandlerInterceptorAdapter {


    /**
     * 注解方法执行之前,执行这里
     * @author Linyb
     * @since 2017/9/25 15:54
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod methodHandler=(HandlerMethod) handler;
        SelfAnno selfAnno = methodHandler.getMethodAnnotation(SelfAnno.class);

        System.out.println("preHandle:"+selfAnno.print());

        return super.preHandle(request, response, handler);
    }

    /**
     * 注解方法执行之后,执行这里,这边可以改遍返回的 ModelAndView
     * @author Linyb
     * @since 2017/9/25 15:54
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerMethod methodHandler=(HandlerMethod) handler;
        SelfAnno selfAnno = methodHandler.getMethodAnnotation(SelfAnno.class);

        System.out.println("postHandle:"+selfAnno.print());
        super.postHandle(request, response, handler, modelAndView);
    }
    /**
     * 可以根据ex 判断是否发生了异常，进行日志记录
     * @author Linyb
     * @since 2017/9/25 16:04
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerMethod methodHandler=(HandlerMethod) handler;
        SelfAnno selfAnno = methodHandler.getMethodAnnotation(SelfAnno.class);

        System.out.println("afterCompletion:"+selfAnno.print());
        super.afterCompletion(request, response, handler, ex);
    }
}
